﻿using HealthcareSystem.API.Read.Application.Command.Team;
using HealthcareSystem.API.Read.DTO.Team;
using HealthcareSystem.Domain.BasicSettings.Team;
using MediatR;
using Microsoft.AspNetCore.Server.HttpSys;
using System.Numerics;
using WeekExam.PassPort.ErrorCode;
using WeekExam.PassPort.Infrastructure.Interface;

namespace HealthcareSystem.API.Read.Application.CommandHandel.Team
{
    /// <summary>
    /// 团队请求查询
    /// </summary>
    public class TeamQueryCommandHandler : IRequestHandler<TeamQueryCommand, ApiResult<ApiPaging<List<TeamTableDTO>>>>
    {
        private readonly IBaseRepository<TeamTable> teamRep;

        public TeamQueryCommandHandler(IBaseRepository<TeamTable> teamRep)
        {
            this.teamRep = teamRep;
        }

        public Task<ApiResult<ApiPaging<List<TeamTableDTO>>>> Handle(TeamQueryCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<List<TeamTableDTO>>> result = new ApiResult<ApiPaging<List<TeamTableDTO>>>();
            result.Code=ResultCode.Success;
            result.Message = ResultCode.查询成功.ToString();

            var res = from a in teamRep.GetAll()
                      where !a.IsDelete
                      select new TeamTableDTO
                      {
                          TeamId=a.TeamId,
                          TeamName=a.TeamName,
                          ParentTeam=a.ParentTeam,
                          Charge=a.Charge,
                          TeamTags=a.TeamTags   ,
                          TeamStatus=a.TeamStatus,
                          Phone=a.Phone,
                          TeamProfile=a.TeamProfile,
                          IsDelete=a.IsDelete

                      };
            if (request.TeamStatus != null)
            {
                res=res.Where(x=>x.TeamStatus==request.TeamStatus);
            }
            if (!string.IsNullOrEmpty(request.TeamName))
            {
                res=res.Where(x=>x.TeamName.Contains(request.TeamName));
            }
            //总条数
            var totalcount=res.Count();
            //总页数
            var totalpage = (int)Math.Ceiling(totalcount * 1.0 / request.Pagsize);
            //排序
            res = res.OrderByDescending(x => x.TeamId).Skip((request.Pagindex - 1) * request.Pagsize).Take(request.Pagsize);

            ApiPaging<List<TeamTableDTO>> paging = new ApiPaging<List<TeamTableDTO>>();
            paging.totalCount = totalcount;
            paging.totalPage = totalpage;
            paging.Data = res.ToList();
            result.Data = paging;
            return Task.FromResult(result);
        }
    }
}
